package me.zhengjie.controller.PPOutBoundController;

import cn.hutool.core.util.ObjectUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import me.zhengjie.annotation.Log;
import me.zhengjie.pojo.sqlServer.*;
import me.zhengjie.ppService.PPInventoryService;
import me.zhengjie.ppService.PPOutBoundService;
import me.zhengjie.pojo.PPOutBoundInvertoryUI;
import me.zhengjie.pojo.PPOutBoundParameter;
import me.zhengjie.pojo.Resp;
import me.zhengjie.ppService.PPStationService;
import me.zhengjie.repository.PPInfoRepository;
import me.zhengjie.service.PPInfoService;
import me.zhengjie.service.PPOutboundMissionService;
import me.zhengjie.service.PPOutboundOrderDetailService;
import me.zhengjie.service.PPOutboundOrderService;
import me.zhengjie.service.dto.PPOutboundOrderDetailQueryCriteria;
import me.zhengjie.service.dto.PPOutboundOrderDto;
import me.zhengjie.service.dto.PPOutboundOrderQueryCriteria;
import me.zhengjie.utils.PageResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author: xinglin
 * @CreateTime: 2024-08-19
 * @Description: pp出库管理
 * @Version: 1.0
 */


@RestController
@RequiredArgsConstructor
@Api(tags = "出库管理")
@RequestMapping("/api/ppOutBound")
public class PPOutBoundController {

    private final PPOutboundOrderService ppOutboundOrderService;
    private final PPOutboundMissionService ppOutboundMissionService;
    private final PPOutboundOrderDetailService ppOutboundOrderDetailService;
    private final PPOutBoundService ppOutBoundService;
    private final PPInventoryService ppInventoryService;
    private final PPInfoService ppInfoService;
    private final PPInfoRepository ppInfoRepository;
    private final PPStationService ppStationService;

    private final  Logger ppLog = LoggerFactory.getLogger("pp");



    @GetMapping
    @Log("查询出库单")
    @ApiOperation("查询出库单")
    @PreAuthorize("@el.check('ppOutboundOrder:list')")
    public ResponseEntity<PageResult<PPOutboundOrderDto>> queryOutBoundOrder(PPOutboundOrderQueryCriteria criteria, Pageable pageable) {
        return new ResponseEntity<>(ppOutboundOrderService.queryAll(criteria, pageable), HttpStatus.OK);
    }


    @GetMapping("/getOrderPPInfoList/{orderId}")
    @Log("查询库存中的PPInfo")
    @ApiOperation("查询库存中的PPInfo")
    @PreAuthorize("@el.check('ppInfo:list')")
    public ResponseEntity<PageResult<PPOutBoundInvertoryUI>> queryPpInfo(PPOutboundOrderDetailQueryCriteria criteria, Pageable pageable, @PathVariable Integer orderId) {
        return new ResponseEntity<>(ppInfoService.queryAllByOrderDetails(criteria,pageable,orderId),HttpStatus.OK);
    }




    @Log("查找出库单明细")
    @ApiOperation("查找出库单明细")
    @GetMapping(value = "/getPPOutboundOrderDetail/{orderId}")
    public List<PPOutboundOrderDetail> getOutBoundDetail(@PathVariable("orderId") Integer orderId) {
        try {
            return ppOutboundOrderDetailService.findByOrderId(orderId);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }


    @Log("查找库存")
    @ApiOperation("查找库存")
    @PostMapping(value = "/getInventory")
    public Resp getInventory(@RequestBody List<PPOutBoundParameter> parameter) {
        List<PPInventory> inventories = ppOutBoundService.getInventoryInfo(parameter);
        if (inventories.isEmpty()) {
            return Resp.builder()
                    .status(200)
                    .data("inventoryReports", inventories)
                    .msg("没有匹配到库存信息")
                    .build();
        }

        return Resp.builder()
                .status(200)
                .data("inventoryReports", inventories)
                .build();

    }


    //出库站类型1
    @Log("创建对应站点的出库单")
    @ApiOperation("创建对应站点的出库单")
    @PostMapping(value = "/createPPOutBoundOrder")
//    @PreAuthorize("@el.check('createPPOutBoundOrder:list')")
    public Resp createStationOutBoundOrder(@RequestBody List<PPOutBoundParameter> parameters) {

        try {
            if (ppInventoryService.OutBoundOrderAllow(parameters).getAllow()) {
                PPOutboundOrder ppOutboundOrder = ppOutBoundService.createOrder(parameters);
                return Resp.builder()
                        .data("orderId", ppOutboundOrder.getId())
                        .status(200)
                        .msg("创建出库单成功")
                        .build();
            } else {
                return Resp.builder()
                        .data("ppBatchs", ppInventoryService.OutBoundOrderAllow(parameters).getPpBatchs())
                        .status(501)
                        .msg("出库单部分库存pp正在出库或被锁定，无法创建出库单！")
                        .build();

            }

        } catch (Exception e) {
            return Resp.builder()
                    .status(500)
                    .msg("创建出库单信息不完整，请校验数据！")
                    .build();
        }
    }



    //出库站类型0
    @Log("新增出库单通过ppBatch")
    @ApiOperation("创建出库单不需要站点")
    @PostMapping(value = "/createPPOutBoundOrderWithoutStation")
//    @PreAuthorize("@el.check('createPPOutBoundOrder:list')")
    public Resp createOutBoundOrderWithout(@RequestBody List<PPOutBoundParameter> parameters) {

        try {
            List<String>  unExistppBatchs = new ArrayList<>();
            for (PPOutBoundParameter ppOutBoundParameter : parameters) {
                PPInfo  newPpInfo = ppInfoRepository.getPPInfoByPpBatch(ppOutBoundParameter.getPpBatch());
                if (newPpInfo == null){
                    unExistppBatchs.add(ppOutBoundParameter.getPpBatch());
                }
            }


            if (unExistppBatchs.size()>0){
                ppLog.info("创建出库单时，以下批次不存在：{}",unExistppBatchs);
            }

            if (ppInventoryService.OutBoundOrderAllow(parameters).getAllow()) {
                //查询工作站
                PPStation ppStation = ppStationService.getStationByCode(parameters.get(0).getOutStation());
                PPOutboundOrder ppOutboundOrder = new PPOutboundOrder();
                if (ppStation.getStationType()==0) {
                    ppOutboundOrder = ppOutBoundService.createOrderWithoutStation(parameters);
                }else {
                    ppOutboundOrder = ppOutBoundService.createOrder(parameters);
                }

                if (ObjectUtil.isNotEmpty(ppOutboundOrder)) {

                    return Resp.builder()
                            .data("orderId", ppOutboundOrder.getId())
                            .data("unExistPpBatchs",unExistppBatchs)
                            .status(200)
                            .msg("创建出库单成功")
                            .build();

                }else {
                    return Resp.builder()
                            .status(500)
                            .msg("创建出库单失败,所选PP物料为过期物料")
                            .build();
                }
            } else {
                return Resp.builder()
                        .data("ppBatchs", ppInventoryService.OutBoundOrderAllow(parameters).getPpBatchs())
                        .status(501)
                        .msg("出库单部分库存pp正在出库或被锁定，无法创建出库单！")
                        .build();

            }

        } catch (Exception e) {
            return Resp.builder()
                    .status(500)
                    .msg("创建出库单信息不完整，请校验数据！")
                    .build();
        }
    }


    @Log("通过板子批号创建出库单")
    @ApiOperation("通过板子批号创建出库单")
    @PostMapping(value = "/createPPOutBoundOrderByPPBatch")
//    @PreAuthorize("@el.check('createPPOutBoundOrder:list')")
    public Resp createOutBoundOrder(@RequestBody List<String> palletBatchs) {

        try {
            List<PPOutBoundParameter> parameters = new ArrayList<>();

            List<String>  unExistPalletBatchs = new ArrayList<>();

            if (unExistPalletBatchs.size()>0){
                ppLog.info("创建出库单时，以下批次不存在：{}",unExistPalletBatchs);
            }

            List<PPInfo> ppInfos = new ArrayList<>();

            for (String palletBatch : palletBatchs) {
                List<PPInfo>   newPpInfos = ppInfoRepository.findByPalletBatch(palletBatch);
                if (newPpInfos == null){
                    unExistPalletBatchs.add(palletBatch);
                }else {
                    ppInfos.addAll(newPpInfos);
                }
            }

            for (PPInfo ppInfo : ppInfos) {
                PPOutBoundParameter ppOutBoundParameter = new PPOutBoundParameter();
                ppOutBoundParameter.setPpBatch(ppInfo.getPpBatch());
                ppOutBoundParameter.setBatch(ppInfo.getBatch());
                parameters.add(ppOutBoundParameter);
            }

            if (ppInventoryService.OutBoundOrderAllow(parameters).getAllow()) {
                PPOutboundOrder ppOutboundOrder = ppOutBoundService.createOrderWithoutStation(parameters);

                if (ppOutboundOrder!=null) {

                        return Resp.builder()
                                .data("orderId", ppOutboundOrder.getId())
                                .data("unExistPpBatchs",unExistPalletBatchs)
                                .status(200)
                                .msg("创建出库单成功")
                                .build();

                }else {
                    return Resp.builder()
                            .status(500)
                            .msg("创建出库单失败,所选PP物料为过期物料")
                            .build();
                }
            } else {
                return Resp.builder()
                        .data("ppBatchs", ppInventoryService.OutBoundOrderAllow(parameters).getPpBatchs())
                        .status(501)
                        .msg("出库单部分库存pp正在出库或被锁定，无法创建出库单！")
                        .build();

            }

        } catch (Exception e) {
            return Resp.builder()
                    .status(500)
                    .msg("创建出库单信息不完整，请校验数据！")
                    .build();
        }
    }





    @Log("开始执行出库单")
    @ApiOperation("开始执行出库单")
    @PostMapping(value = "/startOrder/{orderId}")
//    @PreAuthorize("@el.check('startPPOutBoundOrder:list')")
    public Resp StartOrder(@PathVariable("orderId") Integer orderId) {
//        List<PPOutboundMission> ppOutBoundMissions = ppOutboundMissionService.findPPOutBoundMissionByOrderId(orderId);
//        ppOutboundMissionService.startMission(ppOutBoundMissions);
//        ppOutBoundService.createOutTask(ppOutBoundMissions);
//        ppOutboundOrderService.startOrder(orderId);
        try {
            ppOutBoundService.startOutBoundOrder(orderId);
            return Resp.builder()
                    .status(200)
                    .msg("任务已下发至执行列表")
                    .build();
        } catch (Exception e) {
            return Resp.builder()
                    .status(500)
                    .msg(e.getMessage())
                    .build();
        }

    }


    @Log("删除出库单")
    @ApiOperation("删除出库单")
    @DeleteMapping(value = "/deleteOrder/{orderId}")
    public Resp deleteOrder(@PathVariable("orderId") Integer orderId) {
        try {
            ppOutBoundService.deletePPOutBoundOrder(orderId);
            return Resp.builder()
                    .status(200)
                    .msg("删除出库单成功！")
                    .build();
        } catch (Exception e) {
            return Resp.builder()
                    .status(500)
                    .msg("删除出库单失败！")
                    .build();
        }
    }


//    @Log("添加出库单，锁库存")
//    @ApiOperation("添加出库单，锁库存")
//    @PostMapping("/add/{ppBatch}")
//    public Resp add(@PathVariable String ppBatch) {
//
//        try {
//
//            PPInventory ppInventory = ppInventoryRepository.findByPpBatch(ppBatch);
//            ppInventory.setLockStatus(0);
//            ppInventoryRepository.save(ppInventory);
//
//            return Resp.builder()
//                    .status(200)
//                    .msg("添加出库单成功！")
//                    .build();
//        } catch (Exception e) {
//            return Resp.builder()
//                    .status(500)
//                    .msg("添加出库单失败！")
//                    .build();
//        }
//    }

//    @Log("删除出库单，释放库存")
//    @ApiOperation("删除出库单，释放库存")
//    @PostMapping("/delete/{ppBatch}")
//    public Resp delete(@PathVariable String ppBatch) {
//
//        try {
//
//            PPInventory ppInventory = ppInventoryRepository.findByPpBatch(ppBatch);
//            ppInventory.setLockStatus(1);
//            ppInventoryRepository.save(ppInventory);
//
//            return Resp.builder()
//                    .status(200)
//                    .msg("删除出库单成功！")
//                    .build();
//        } catch (Exception e) {
//            return Resp.builder()
//                    .status(500)
//                    .msg("删除出库单失败！")
//                    .build();
//        }
//    }


}
